<template>
  <div class="filters-container">
    <el-form
      :inline="true"
      :model="queryParams"
      label-width="100px"
      label-position="right"
      size="small"
      class="filter-form-inline"
    >
      <el-row
        :gutter="20"
        style="width:100%;margin-left: 0px; margin-right: 0px"
      >
        <el-col
          :xs="3"
          :lg="4"
          style="max-width: 50%"
        >
          <el-form-item
            label="付款方类型"
            style="width:100%"
            prop="customerType"
          >
            <el-select
              v-model="queryParams.customerType"
              clearable
              style="width: 100%"
              placeholder="付款方类型"
              @change="handlSearch"
            >
              <el-option
                key="全部"
                label="全部"
                value=""
              />
              <el-option
                v-for="(item, idx) in returnTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 50%"
        >
          <el-form-item
            label="付款方名称"
            style="width:100%"
            prop="customerId"
          >
            <el-select
              v-model="queryParams.customerId"
              style="width: 100%"
              placeholder="选择付款方"
              filterable
              remote
              reserve-keyword
              :remote-method="customerQuerySearch"
              :loading="customerLoading"
              :disabled="queryParams.customerType?false:true"
              clearable
              @change="handlSearch"
              @clear="()=>queryParams.customerId=undefined"
            >
              <el-option
                v-for="(item, idx) in customerOption"
                :key="item.id"
                :label="item.customerName"
                :value="item.customerId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="4"
          style="max-width: 50%"
        >
          <el-form-item
            label="负责销售职员"
            style="width:100%"
            prop="headId"
          >
            <el-select
              v-model="queryParams.headId"
              clearable
              style="width: 100%"
              placeholder="负责营销职员"
              @change="handlSearch"
              @clear="officeClerkClear"
            >
              <el-option
                v-for="(item, idx) in officeClerkOption"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="4"
          :lg="6"
          style="max-width: 50%"
        >
          <el-form-item
            label="回款金额"
            style="width:100%"
          >
            <div style="display:flex;">
              <el-input
                v-model="queryParams.minAmount"
                placeholder="最小回款金额"
                oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                @blur="()=>queryParams.minAmount = queryParams.minAmount?Number(queryParams.minAmount):undefined"
              />
              <span style="padding: 0px 4px;color: #666">-</span>
              <el-input
                v-model="queryParams.maxAmount"
                placeholder="最大回款金额"
                oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                @blur="()=>queryParams.maxAmount = queryParams.maxAmount?Number(queryParams.maxAmount):undefined"
              />
            </div>
          </el-form-item>
        </el-col>
        <div style="width: 70px;display:inline-block;margin:0px 20px">
          <el-form-item style="width: 100%">
            <more-search-btn
              v-model:is-more="isMore"
              @onClick="moreSearchClick"
            />
          </el-form-item>
        </div>
        <el-col
          :xs="2"
          :lg="3"
          style="max-width: 140px"
        >
          <el-form-item style="width:140px">
            <el-button
              class="border-btn"
              @click="handlReset"
            >重置</el-button>
            <el-button
              type="primary"
              class="main-btn"
              @click="handlSearch"
            >搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        v-if="isMore"
        :gutter="20"
        style="margin-left: 0px; margin-right: 0px"
      >
        <el-col
          :xs="3"
          :lg="9"
          style="max-width: 50%"
        >
          <el-form-item
            label="关键字"
            style="width:100%"
            prop="keyWord"
          >
            <el-input
              v-model="queryParams.keyWord"
              style="width: 100%"
              placeholder="请输入付款开户行、付款账号、收款记录编号关键字"
              @clear="handlSearch"
            />
          </el-form-item>
        </el-col>
        <!--
        <el-col
          :xs="3"
          :lg="7"
          style="max-width: 50%"
        >
          <el-form-item
            label="付款日期"
            style="width:100%"
            prop="payTimeArr"
          >
            <date-range-picker
              v-model:date="queryParams.payTimeArr"
              style="width: 100%"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="payTimeChange"
            />
          </el-form-item>
        </el-col>
        -->
      </el-row>
    </el-form>
  </div>
  <table-view
    header-cell-class-name="table-header"
    :data="tableData"
    border
    :cell-style="cellStyle"
    :visible="isMore"
    @row-click="aloneClick"
  >
    <el-table-column
      label="收款记录编号"
      prop="receiveNumber"
      header-align="center"
      align="center"
      :width="140"
      show-overflow-tooltip
      fixed="left"
    />
    <el-table-column
      label="付款方类型"
      prop="customerType"
      header-align="center"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        {{ getLabel('returned_money_type', scope.row.customerType) }}
      </template>
    </el-table-column>
    <el-table-column
      label="付款方名称"
      prop="customerName"
      header-align="center"
      :min-width="160"
      show-overflow-tooltip
    >
      <template #default="scope">
        {{ scope.row.customerName }}
      </template>
    </el-table-column>
    <el-table-column
      label="金额(元)"
      prop="receiveAmount"
      header-align="center"
      align="right"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ moneyFormat(scope.row.receiveAmount) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="付款开户行"
      prop="bankName"
      header-align="center"
      :min-width="160"
      show-overflow-tooltip
    />
    <el-table-column
      label="付款开户行"
      prop="bankNumber"
      header-align="center"
      :min-width="160"
      show-overflow-tooltip
    />
    <el-table-column
      label="付款日期"
      header-align="center"
      align="center"
      :width="140"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ dateFormat('yyyy-mm-dd', scope.row.payTime) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="负责销售职员"
      align="center"
      header-align="center"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ scope.row.headName }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="状态"
      align="center"
      header-align="center"
      :width="120"
      show-overflow-tooltip
      fixed="right"
    >
      <template #default="scope">
        <span>
          {{ getLabel('returned_money_status',scope.row.receiveStatus) }}
        </span>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      header-align="center"
      fixed="right"
      :min-width="100"
    >
      <template #default="scope">
        <template v-if="navigation==='returnedRecords'">
          <template v-if="scope.row.receiveStatus==='-1'">
            <el-button
              v-auth="{v: ['crm:returnedRecords:returnedMoney:all']}"
              type="text"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              v-auth="{v: ['crm:returnedRecords:returnedMoney:all']}"
              type="text"
              class="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </template>
        <template v-else>
          <el-button
            v-auth="{v: ['crm:internalControl:finance:all'], bool: scope.row.receiveStatus==='1'}"
            type="text"
            @click="handleConfirm(scope.row)"
          >确认</el-button>
          <el-button
            v-auth="{v: ['crm:internalControl:finance:all'], bool: scope.row.receiveStatus==='2'&&scope.row.customerType!=='seller'}"
            type="text"
            class="danger"
            @click="handleSplit(scope.row)"
          >分账</el-button>
        </template>
      </template>
    </el-table-column>

  </table-view>
  <Pagination
    v-model:page="queryParams.page"
    v-model:limit="queryParams.pageSize"
    style="display: flex; justify-content: flex-end"
    :total="total"
    @pagination="handlList"
  />
  <!-- 新建收款 -->
  <create-payee
    ref="returnedMoneyRef"
    @onSuccess="onSuccess"
  />
  <!-- 收款详情 -->
  <detail-drawer
    ref="detailDrawer"
    custom-title
  >
    <template #title>
      <div
        class="draw-title"
        style="display:flex;justify-content:space-between;"
      >
        <div class="title-left">
          <span style="margin-right:5px;">收款详情 - {{ rowData?.receiveNumber }}</span>
          <el-tag
            type="warning"
            size="small"
          >
            <span>
              {{ getLabel('returned_money_status',rowData?.receiveStatus) }}
            </span>
          </el-tag>
        </div>
        <div class="title-right">
          <template v-if="navigation==='returnedRecords'">
            <template v-if="rowData?.receiveStatus==='-1'">
              <el-button
                v-auth="{v: ['crm:returnedRecords:returnedMoney:all']}"
                type="primary"
                size="small"
                @click="handleEdit(rowData)"
              >编辑</el-button>
              <el-button
                v-auth="{v: ['crm:returnedRecords:returnedMoney:all']}"
                type="primary"
                size="small"
                @click="handleDelete(rowData)"
              >删除</el-button>
            </template>
          </template>
          <template v-else>
            <el-button
              v-auth="{v: ['crm:internalControl:finance:all'], bool: rowData?.receiveStatus==='1'}"
              type="primary"
              size="small"
              @click="handleConfirm(rowData)"
            >确认</el-button>
            <el-button
              v-auth="{v: ['crm:internalControl:finance:all'], bool: rowData?.receiveStatus==='2'&&rowData?.customerType!=='seller'}"
              type="primary"
              size="small"
              @click="handleSplit(rowData)"
            >分账</el-button>
          </template>
        </div>
      </div>
    </template>
    <template #contents>
      <div class="drawer-content">
        <div class="history-list">
          <item-title title="基本信息" />
          <payee-info :detail-data="rowData" />
        </div>
        <div
          v-if="rowData?.receiveStatus === '3'"
          class="history-list"
          style="margin-bottom: 20px"
        >
          <item-title title="分账处理结果" />
          <payee-split-info :row="rowData" />
        </div>
        <div class="history-list">
          <item-title title="操作记录" />
          <operation-view
            :id="rowData.id"
            mode="receive_money"
          />
        </div>
      </div>
    </template>
  </detail-drawer>
  <!-- 收款确认 -->
  <confirm-money
    ref="confirmMoney"
    @confirmSuccess="handlList"
    @split="toSplit"
  />
  <!-- 分账 -->
  <split-money
    ref="splitMoney"
    @splitSuccess="handlList"
  />
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRouter } from 'vue-router'
import { crmStore } from '@CRM/store'

export default {
  name: 'Receivable',
  components: {
    createPayee: defineAsyncComponent(() =>
      import('../modules/createPayee.vue')
    ),
    payeeInfo: defineAsyncComponent(() => import('../modules/payeeInfo.vue')),
    payeeSplitInfo: defineAsyncComponent(() =>
      import('../modules/payeeSplitInfo.vue')
    ),
    confirmMoney: defineAsyncComponent(() =>
      import('../modules/confirmMoney.vue')
    ),
    splitMoney: defineAsyncComponent(() => import('../modules/splitMoney.vue')),
  },
  props: {
    navigation: {
      type: String,
      default: 'returnedRecords',
    },
  },
  setup(props, context) {
    const api = inject('api')
    const router = useRouter()
    const returnedMoneyRef = ref(null)
    // 搜索对象
    var data = reactive({
      isMore: false,
      userInfo: crmStore.getters['user/userInfo'],
      splitMoney: null,
      confirmMoney: null,
      queryParams: {
        customerId: undefined,
        customerType: '',
        maxAmount: null,
        minAmount: null,
        payTimeArr: [],
        start: null,
        end: null,
        headId: undefined,
        dealId: undefined,
        keyWord: '',
        from: props.navigation === 'returnedRecords' ? '1' : undefined,
        pageSize: 20,
        page: 1,
      },
      tableData: [],
      total: 0,
      returnTypeOptions:
        crmStore.getters['dictionary/getDictionary']['returned_money_type'],
      distributeOption: [],
      customerOption: [],
      officeClerkOption: crmStore.getters['company/getHeadOptions'],
      financeOption: [],
      customerLoading: false,
      detailDrawer: null,
      rowData: null,
    })
    const currentInstance = getCurrentInstance()
    const moreSearchClick = () => {
      data.isMore = !data.isMore
    }
    // 新建回款
    const handleCreate = () => {
      returnedMoneyRef.value.open({ types: 'create', data: null })
    }
    // 回款编辑
    const handleEdit = (row) => {
      returnedMoneyRef.value.open({ types: 'edit', data: { ...row }})
    }
    // 到账时间范围变化
    const payTimeChange = (val) => {
      if (val.length) {
        data.queryParams.start = val[0]
        data.queryParams.end = val[1]
      } else {
        data.queryParams.start = null
        data.queryParams.end = null
      }
    }
    const officeClerkClear = () => {
      data.queryParams.headId = undefined
    }
    // 获取列表
    const handlList = () => {
      api.returnedAndReceivable
        .RETURNEDMONEY_LIST(data.queryParams)
        .then((res) => {
          if (res.code === 0) {
            data.tableData = res.data.list || []
            data.total = res.data.total
            // 判断如果在抽屉操作，更新rowData数据
            if (data.rowData) {
              var item = data.tableData.find((p) => p.id === data.rowData.id)
              if (item) {
                data.rowData = item
              } else {
                data.rowData = null
                data.value.close()
              }
            }
          }
        })
    }

    // 获取下属职员列表
    const getUserList = () => {
      console.log(data.userInfo)
      var subdata = {
        userId: data.userInfo?.ID,
        types: 'lower',
      }
      api.common.USER_LIST(subdata).then((res) => {
        if (res.code === 0) {
          data.officeClerkOption = res.data || []
        }
      })
    }

    // 删除回款
    const handleDelete = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '数据删除后不可恢复，确定删除？',
          title: '回款删除',
        })
        .then(() => {
          api.returnedAndReceivable
            .RETURNEDMONEY_DELETE({
              id: row.id,
            })
            .then((res) => {
              if (res.code) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              } else {
                handlList()
              }
            })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const customerQuerySearch = async(queryString, cb) => {
      data.customerLoading = true
      const a = {
        customerType: 'agent',
        keyWord: queryString,
      }
      let results = []
      const res =
        await api.returnedAndReceivable.RECEIVABLE_CUSTOMER_LIST_BY_TYPE(a)
      if (res.code === 0) {
        data.customerLoading = false
        results = res.data.list || []
        data.customerOption = results
      }
    }

    // 搜索
    const handlSearch = () => {
      data.queryParams.page = 1
      handlList()
    }

    // 重置
    const handlReset = () => {
      data.queryParams = {
        customerId: undefined,
        customerType: '',
        maxAmount: null,
        minAmount: null,
        payTimeArr: [],
        start: null,
        end: null,
        headId: undefined,
        keyWord: '',
        from: props.navigation === 'returnedRecords' ? '1' : undefined,
        pageSize: 20,
        page: 1,
      }
      handlList()
    }

    // 单机表格
    const aloneClick = (row, column, event) => {
      console.log(row, column, event)
      if (column.label === '操作') return
      data.rowData = row
      data.detailDrawer.open()
    }

    // 鼠标样式
    const cellStyle = () => {
      return 'cursor:pointer;'
    }

    const onSuccess = () => {
      handlList()
    }

    // 分账
    const handleSplit = (row) => {
      data.rowData = row
      data.splitMoney.open(data.rowData)
    }
    // 收款确认
    const handleConfirm = (row) => {
      data.rowData = row
      data.confirmMoney.open(data.rowData)
    }
    const toSplit = async() => {
      var res = await api.returnedAndReceivable.RETURNEDMONEY_LIST(
        data.queryParams
      )
      if (res.code === 0) {
        data.tableData = res.data.list || []
        data.total = res.data.total
        // 判断如果在抽屉操作，更新rowData数据
        if (data.rowData) {
          var item = data.tableData.find((p) => p.id === data.rowData.id)
          if (item) {
            data.rowData = item
          } else {
            data.rowData = null
            data.value.close()
          }
        }
      }
      data.splitMoney.open(data.rowData)
    }

    onMounted(() => {
      if (props.navigation === 'returnedRecords') {
        getUserList()
      }
      handlList()
    })

    return {
      returnedMoneyRef,
      ...toRefs(data),
      handleCreate,
      handlList,
      handlSearch,
      handlReset,
      aloneClick,
      cellStyle,
      onSuccess,
      payTimeChange,
      handleEdit,
      handleDelete,
      customerQuerySearch,
      moreSearchClick,
      officeClerkClear,
      handleSplit,
      handleConfirm,
      toSplit,
    }
  },
}
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
